package com.zshan.clinic.admin.service.customer;

import com.zshan.clinic.admin.entity.vo.CmUserVo;
import com.zshan.clinic.common.enums.YesOrNoEnum;
import com.zshan.clinic.common.exception.BusinessFailException;
import com.zshan.clinic.common.util.page.PageInfo;
import com.zshan.clinic.common.util.page.PageUtils;
import com.zshan.clinic.common.util.string.StringUtil;
import com.zshan.clinic.database.dao.CmUserMapper;
import com.zshan.clinic.database.model.CmUser;
import com.zshan.clinic.database.model.CmUserExample;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * C端用户
 */
@Service
@Slf4j
public class CmUserService {

    @Autowired
    private CmUserMapper cmUserMapper;

    /**
     * 查询用户信息
     * @param clinicId
     * @param cmUserId
     * @return
     */
    public CmUserVo getCmUserInfo(Long clinicId, Long cmUserId) {
        CmUser cmUser = getCmUserById(cmUserId);
        if(cmUser == null){
            return null;
        }
        CmUserVo cmUserVo = new CmUserVo();
        BeanUtils.copyProperties(cmUser,cmUserVo);
        return cmUserVo;
    }

    /**
     * 根据openid查询用户
     * @param clinicId
     * @param openid
     * @return
     */
    public CmUser getCmUserByOpenid(Long clinicId,String openid){
        CmUserExample example = new CmUserExample();
        CmUserExample.Criteria criteria = example.createCriteria();
        criteria.andClinicIdEqualTo(clinicId);
        criteria.andOpenidEqualTo(openid);
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        List<CmUser> cmUserList = cmUserMapper.selectByExample(example);
        return CollectionUtils.isEmpty(cmUserList) ? null : cmUserList.get(0);
    }

    /**
     * 分页查询C端用户
     * @param nickName 用户名（可选条件）
     * @param pageNo 页码
     * @param pageSize 每页条数
     * @return 分页结果
     */
    public PageInfo<CmUser> getCmUserListByCondition(String nickName, Integer pageNo, Integer pageSize) {
        CmUserExample example = new CmUserExample();
        CmUserExample.Criteria criteria = example.createCriteria();
        if (StringUtil.isNotBlank(nickName)) {
            criteria.andNickNameLike("%" + nickName + "%");
        }
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        Long totalCount = cmUserMapper.countByExample(example);
        if (totalCount == null || totalCount == 0) {
            return PageInfo.build();
        }
        example.setOffset(PageUtils.getOffset(pageNo, pageSize));
        example.setLimit(pageSize);
        example.setOrderByClause("create_time desc");
        List<CmUser> list = cmUserMapper.selectByExample(example);
        return new PageInfo<>(totalCount, list);
    }

    /**
     * 添加C端用户
     * @param cmUser 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public CmUser addCmUser(CmUser cmUser) {
        validateCmUser(cmUser);
        cmUser.setIsDelete(YesOrNoEnum.NO.getValue());
        cmUser.setIsEnabled(YesOrNoEnum.YES.getValue());
        cmUser.setCreateTime(new Date());
        cmUserMapper.insertSelective(cmUser);
        return cmUser;
    }

    /**
     * 校验C端用户参数
     * @param cmUser 实体
     */
    public void validateCmUser(CmUser cmUser) {
        // TODO: 可补充必填校验、格式校验、唯一性校验等
    }

    /**
     * 根据ID查询C端用户
     * @param cmUserId 主键
     * @return C端用户记录
     */
    public CmUser getCmUserById(Long cmUserId) {
        if (cmUserId == null) {
            return null;
        }
        CmUser cmUser = cmUserMapper.selectByPrimaryKey(cmUserId);
        if (cmUser == null || YesOrNoEnum.YES.getValue().equals(cmUser.getIsDelete())) {
            return null;
        }
        return cmUser;
    }

    /**
     * 修改C端用户
     * @param cmUser 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateCmUser(CmUser cmUser) {
        validateCmUser(cmUser);
        CmUser dbCmUser = getCmUserById(cmUser.getCmUserId());
        if (dbCmUser == null) {
            throw new BusinessFailException("用户不存在");
        }
        cmUser.setUpdateTime(new Date());
        cmUserMapper.updateByPrimaryKeySelective(cmUser);
    }

    /**
     * 删除C端用户（逻辑删除）
     * @param cmUser 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteCmUser(CmUser cmUser) {
        CmUser dbCmUser = getCmUserById(cmUser.getCmUserId());
        if (dbCmUser == null) {
            throw new BusinessFailException("用户不存在");
        }
        dbCmUser.setIsDelete(YesOrNoEnum.YES.getValue());
        dbCmUser.setUpdateUserId(cmUser.getUpdateUserId());
        dbCmUser.setUpdateBy(cmUser.getUpdateBy());
        dbCmUser.setUpdateTime(new Date());
        cmUserMapper.updateByPrimaryKeySelective(dbCmUser);
    }

}
